#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
获取客服账号列表接口
"""

from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

kf_account_list_bp = Blueprint('kf_account_list', __name__)
logger = get_logger(__name__)


@kf_account_list_bp.route('/cgi-bin/kf/account/list', methods=['GET'])
def get_account_list():
    """获取客服账号列表"""
    try:
        # 获取请求参数
        access_token = request.args.get('access_token')
        
        logger.info("获取客服账号列表请求")
        
        # 参数验证
        if not access_token:
            logger.warning("缺少access_token参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing access_token parameter"
            }), 400
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # 验证访问令牌
        if not data_manager.validate_token(access_token):
            logger.warning("无效的access_token")
            return jsonify({
                "errcode": 40014,
                "errmsg": "invalid access_token"
            }), 400
        
        # 获取客服账号列表
        account_list = data_manager.get_accounts()
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"获取客服账号列表成功 - 数量: {len(account_list)}")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "account_list": account_list
        })
        
    except Exception as e:
        logger.error(f"获取客服账号列表失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        return jsonify({
            "errcode": 500,
            "errmsg": "internal error"
        }), 500
